<!DOCTYPE html>
<html lang="en" xmlns:javaScript="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
</head>
<body>
<a onclick="test()" javaScript:void(0)>开始连接WebSocket</a><br>
<textarea id="text">

        </textarea>
<span onclick="btn()">让服务器开始群发消息</span>
<div>
    <h1>聊天内容如下</h1>
    <p id="p"></p>
</div>
</body>
<script>

    function test() {
        if ("WebSocket" in window) {
            console.log("你的浏览器支持webSocket")
            //打开一个webSocket
            var ws = new WebSocket("ws://localhost/demo");
            //连接建立时触发
            ws.onopen = function () {
                console.log("已连接上")
                //发送数据
                ws.send("开始");
            }

            //连接关闭时触发
            ws.onclose = function () {
                console.log("连接已关闭")
            }

            //客户端接收服务端数据时触发
            ws.onmessage = function (eve) {
                console.log(eve)
                var para = document.createElement("p");
                var node = document.createTextNode(eve.data);
                para.appendChild(node);
                document.getElementById("p").appendChild(para);
            }

            //通信发生错误时触发
            ws.onerror = function (eve) {
                console.log(eve)
            }
        }
    }

    function btn() {
        /* console.log(ws.readyState)
         var para = document.createElement("p");
         var node = document.createTextNode("这是一个新的段落。");
         para.appendChild(node);
         ws.send(document.getElementById("p").appendChild(para))*/
    }
</script>
</html>